#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from PIL import Image, ImageDraw
from cv2 import Stitcher
from os import listdir
import sys
import json
from collections import OrderedDict
import cv2
import cv2 as cv
import numpy as np
import math

PIC_NAME = "image_"


def eachFile(filepath):
    pic_name = []
    pathDir = os.listdir(filepath)
    for allDir in pathDir:
        child = os.path.join('%s%s' % (filepath, allDir))
        pic_name.append(child)
    return pic_name


def out_nums(img2):
    b, g, r = cv2.split(img2)  # 三通道分离
    ret1, out = cv2.threshold(b, 0, 100, cv2.THRESH_BINARY)  # 二值化
    # # edges = cv.Canny(out, 100, 200)
    # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
    contours, hierarchy = cv2.findContours(
        out, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  # 检索模式为树形cv2.RETR_TREE，
    # 轮廓存储模式为简单模式cv2.CHAIN_APPROX_SIMPLE，如果设置为 cv2.CHAIN_APPROX_NONE，所有的边界点都会被存储。
    # 第三个参数是轮廓的索引（在绘制独立轮廓是很有用，当设置为 -1 时绘制所有轮廓）。接下来的参数是轮廓的颜色和厚度等
    cv2.drawContours(out, contours, -1, (255, 255, 255), thickness=None,
                     lineType=None, hierarchy=None, maxLevel=None, offset=None)
    n = len(contours)  # 轮廓个数
    print(contours[0].shape, contours[0][1], contours[0][2], contours[0][2])
    ccnt = 0
    for i in range(n):
        length = cv2.arcLength(contours[i], True)  # 获取轮廓长度
        area = cv2.contourArea(contours[i])  # 获取轮廓面积
        if length > 10 and area > 10 and length < 100 and area < 100:
            # print('length['+str(i)+']长度=', length)
            # print("contours["+str(i)+"]面积=", area)
            ccnt += 1
    print("个数：", ccnt)
    # cv2.imshow('out', out)  # 显示原始图像


def Get_Average(list):
    msum = 0
    for item in list:
        msum += item
    a = msum/len(list)
    return [int(a[0][0]), int(a[0][1])]


def eucliDist(A, B):
    return math.sqrt(sum([(a - b) ** 2 for (a, b) in zip(A, B)]))


def remove_hei(img2):
    pose = []

    lengths = 0
    areas = 0
    b, g, r = cv2.split(img2)  # 三通道分离
    # cv2.imshow("b",b)

    ret1, out = cv2.threshold(b, 17, 100, cv2.THRESH_BINARY)  # 二值化
    # # edges = cv.Canny(out, 100, 200)
    # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
    binary, contours, hierarchy = cv2.findContours(
        out, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  # 检索模式为树形cv2.RETR_TREE，
    # 轮廓存储模式为简单模式cv2.CHAIN_APPROX_SIMPLE，如果设置为 cv2.CHAIN_APPROX_NONE，所有的边界点都会被存储。
    # 第三个参数是轮廓的索引（在绘制独立轮廓是很有用，当设置为 -1 时绘制所有轮廓）。接下来的参数是轮廓的颜色和厚度等
    # cv2.drawContours(out, contours, -1, (255, 255, 255), thickness=None,
    #                  lineType=None, hierarchy=None, maxLevel=None, offset=None)

    ROI = np.ones(img2.shape, dtype=np.uint8) * 255  # 感兴趣区域ROI

    n = len(contours)  # 轮廓个数
    # print(n)
    areas = []
    # contours_bk=[]
    for i in range(n):
        length = cv2.arcLength(contours[i], True)  # 获取轮廓长度
        area = cv2.contourArea(contours[i])  # 获取轮廓面积
        areas.append(area)
    id = areas.index(max(areas))
    # contours_bk.append(contours[)])
    cv2.drawContours(ROI, contours, id, (255, 255, 0), -1)  # ROI区域填充白色，轮廓ID1

    # cv2.drawContours(ROI, contours_bk, -1, (255, 255, 0),thickness=3)
    # cv2.imshow("a", ROI)
    # cv2.imshow("b", img2)

    for i in range(img2.shape[0]):
        for j in range(img2.shape[1]):
            if ROI[i, j, 0] == 255 and ROI[i, j, 1] == 255 and ROI[i, j, 2] == 255 and img2[i, j, 0] == 0 and img2[i, j, 1] == 0 and img2[i, j, 2] == 0:
                img2[i, j, 0] = 255
                img2[i, j, 1] = 255
                img2[i, j, 2] = 255
    # cv2.imshow("c", img2)
    # cv2.imwrite("D:/session/session_2/subject_1/images_7/out__re"
    #             ".png",img2)
    return img2


def find_xys(img2,mc):
    

    lengths = 0
    areas = 0
    b, g, r = cv2.split(img2)  # 三通道分离
    # cv2.imshow("b",b)

        
    ret1, out = cv2.threshold(b, mc.threshold_para, 100, cv2.THRESH_BINARY)  # 二值化
    # # edges = cv.Canny(out, 100, 200)
    # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
    binary, contours, hierarchy = cv2.findContours(
        out, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  # 检索模式为树形cv2.RETR_TREE，
    # 轮廓存储模式为简单模式cv2.CHAIN_APPROX_SIMPLE，如果设置为 cv2.CHAIN_APPROX_NONE，所有的边界点都会被存储。
    # 第三个参数是轮廓的索引（在绘制独立轮廓是很有用，当设置为 -1 时绘制所有轮廓）。接下来的参数是轮廓的颜色和厚度等
    # cv2.drawContours(out, contours, -1, (255, 255, 255), thickness=None,
    #                  lineType=None, hierarchy=None, maxLevel=None, offset=None)
    cv2.drawContours(out, contours, -1, (255, 255, 255))
    n = len(contours)  # 轮廓个数
    pose = []
    peo=0
        # print(data)
    for i in range(n):
        length = cv2.arcLength(contours[i], True)  # 获取轮廓长度
        area = cv2.contourArea(contours[i])  # 获取轮廓面积
        # if length > 10 and area > 10 and length < 100 and area < 100:
        mr=area/length*2.0
        if mr<7 and mr>3:
            pose.append(Get_Average(contours[i]))
        elif length > mc.C1 and area > mc.C2 and length < mc.C3 and area < mc.C4: #130
            print(length,area,mr)
            peo+=1
        else:
            print("ERROR:",length,area,mr)
        # else:
        #     _r = length/6.28
        #     _area = 3.14*r*r
            # print("r",r,"_area ", _area,"area ", area)
    print("轮廓个数",n)
    print("检测人数：", len(pose),peo)
    print("threshold_para",mc.threshold_para,"length",mc.C1,"area",mc.C2)
    return pose, out,


def cutpic(imgrgb):
    srcheight = int(imgrgb.shape[0])
    srcwidth = int(imgrgb.shape[1])
    print(srcheight, srcwidth)
    sx = 0
    ex = 0
    ey = 0
    sy = 0

    for i in range(srcheight):
        if(sum(sum(imgrgb[i, ])) != 0):
            if i == 0:
                print(sx)
                print(sum(sum(imgrgb[i, ])))
            else:
                sx = i-1
                print(sx)
                print(sum(sum(imgrgb[i, ])))
            break
    for i in range(srcwidth):
        if(sum(sum(imgrgb[:, i])) != 0):
            if i == 0:
                print(sx)
                print(sum(sum(imgrgb[:, i])))
            else:
                sy = i-1
                print(sy)
                print(sum(sum(imgrgb[:, i])))
            break
    for i in range(srcheight):
        if(sum(sum(imgrgb[srcheight-1-i, ])) != 0):
            ex = srcheight-i+1
            print(ex)
            print(sum(sum(imgrgb[srcheight-1-i, ])))
            break
    for i in range(srcwidth):
        if(sum(sum(imgrgb[:, srcwidth-1-i])) != 0):
            ey = srcwidth-i+1
            print(ey)
            print(sum(sum(imgrgb[:, srcwidth-1-i])))
            break
    imgbk = imgrgb[sx:ex, sy:ey]
    cv2.imwrite('result.png', imgbk)
    return imgbk


def calMatchPose(srcimg, dstimg):
    b1, g1, r1 = cv2.split(srcimg)  # 三通道分离
    b2, g2, r2 = cv2.split(dstimg)  # 三通道分离
    out1 = r1-b1
    out2 = r2-b2
    orb = cv.ORB_create()
    kpSRC, desCat = orb.detectAndCompute(out1, None)
    kpDST, desSmallCat = orb.detectAndCompute(out2, None)
    bf = cv.BFMatcher_create(cv.NORM_HAMMING, crossCheck=True)
    matches = bf.match(desCat, desSmallCat)
    good_match = sorted(matches, key=lambda x: x.distance)
    matchImg = cv.drawMatches(
        out1, kpSRC, out2, kpDST, good_match[: 9], None)
    ma = good_match[0]
    return ((kpSRC[ma.queryIdx].pt[0]-kpDST[ma.trainIdx].pt[0]), (kpSRC[ma.queryIdx].pt[1]-kpDST[ma.trainIdx].pt[1])), matchImg, out1, out2


def show_mached2(pose, bkgdimg, srcimg, dstimg):
    # image = cv2. imread(PATH+"image_"+str(3)+".png")

    dstheight = int(dstimg.shape[0])
    dstwidth = int(dstimg.shape[1])
    srcheight = int(srcimg.shape[0])
    srcwidth = int(srcimg.shape[1])
    for i in range(dstheight):
        for j in range(dstwidth):
            bkgdimg[i+200, j+400] = dstimg[i, j]
    for i in range(srcheight):
        for j in range(srcwidth):
            bkgdimg[i-int(pose[1])+200, j-int(pose[0])+400] = srcimg[i, j]
    return bkgdimg


def read_client_path(examRound):
    path_name = "D:/session/session_2/subject_1/client_path_" + \
        str(examRound)+".json"
    with open(path_name, 'r') as load_f:
        # with open("./sesson2/subject1/subject_1/client_path_6.json", 'r') as load_f:
        load_dict = json.load(load_f)
        # print(load_dict['race_time'])
        # print(load_dict['send_id'])
        # print(load_dict['image_path'])
    return load_dict['send_id'], load_dict['image_path']


def toJons(sum, id, path):
    x = OrderedDict()
    x["rescue_people_total"] = sum
    x["operate_id"] = id
    x["pic_path"] = path
    with open('D:/session/session_2/subject_1/team_path_'+str(id)+'.json', 'w', encoding='utf-8') as f:
        f.write(json.dumps(x, ensure_ascii=False, indent=4))
